package spring.security.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TimeInterceptor implements HandlerInterceptor {

	//控制器方法之后(异常之后会运行)
	//拦截器可以拿到请求体,响应体,请求的方法,以及异常
	//但是拿不到方法的参数值
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("TimeInterceptor  afterCompletion");
		Long end = new Date().getTime();
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time filter: 耗时" + (end - start));
		//如果有异常处理的Handler,那么ex就是null,是因为在进入after方法之前,异常就已经被处理了,
		//如果在没有处理的情况下,继续会进入到Spring的异常处理控制器org.springframework.boot.autoconfigure.web.BasicErrorController
		//拦截器会拦截所有控制器Controller的方法调用,包括Spring内置的控制器
		System.out.println(ex);
	}
	
	//控制器方法之后(异常之后不会运行)
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3)
			throws Exception {
		System.out.println("TimeInterceptor  postHandle");
		Long end = new Date().getTime();
		Long start = (Long) request.getAttribute("startTime");
		System.out.println("time filter: 耗时" + (end - start));
	}

	//控制器方法之前
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("TimeInterceptor  preHandle");
		request.setAttribute("startTime", new Date().getTime());
		String name = ((HandlerMethod)handler).getBean().getClass().getName();
		System.out.println(name);
		String name2 = ((HandlerMethod)handler).getMethod().getName();
		System.out.println(name2);
		return true;
	}

}
